package com.chr.hongyun.common.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.DeleteObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;

/**
 * 腾讯云存储工具类
 * 创建时间:2023/4/10
 * 创建人:陈浩然
 */
public class TxyUtils {

    public static String secretId = "yours_secretUd";
    public static String secretKey = "yours_secretKey";
    public static String bucketName = "yours_bucketName";

    //上传文件到腾讯云存储
    public static void uploadToTxy(String filePath, String fileName) {
        // 初始化 COS 客户端
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 构造 PutObjectRequest 请求对象
        File file = new File(filePath);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file);

        // 调用 COSClient 的 putObject 方法上传文件
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        // 输出上传结果信息
        System.out.println("Etag: " + putObjectResult.getETag());
        System.out.println("VersionId: " + putObjectResult.getVersionId());

        // 关闭 COS 客户端
        cosClient.shutdown();
    }

    //删除文件
    public static void deleteFileFromTxy(String fileName) {
        // 初始化 COS 客户端
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 构造 DeleteObjectRequest 请求对象
        DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, fileName);

        // 调用 COSClient 的 deleteObject 方法删除文件
        cosClient.deleteObject(deleteObjectRequest);

        // 输出删除成功信息
        System.out.println("Delete object " + fileName + " success.");

        // 关闭 COS 客户端
        cosClient.shutdown();
    }


}
